package com.zhizuobiao.coura.stockhelper;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.zhizuobiao.coura.adapter.CityListAdapter;
import com.zhizuobiao.coura.adapter.ResultListAdapter;
import com.zhizuobiao.coura.city.City;
import com.zhizuobiao.coura.city.LocateState;
import com.zhizuobiao.coura.db.DBManager;
import com.zhizuobiao.coura.utils.MPermissionUtils;
import com.zhizuobiao.coura.utils.StringUtil;
import com.zhizuobiao.coura.view.SideLetterBar;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by coura on 2016/12/29.
 */

public class CityPickerActivity extends AppCompatActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.listview_all_city)
    ListView listviewAllCity;
    @BindView(R.id.tv_letter_overlay)
    TextView tvLetterOverlay;
    @BindView(R.id.side_letter_bar)
    SideLetterBar sideLetterBar;
    @BindView(R.id.listview_search_result)
    ListView listviewSearchResult;
    @BindView(R.id.empty_view)
    ViewGroup emptyView;
    @BindView(R.id.iv_search_clear)
    ImageView ivSearchClear;
    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
    private DBManager dbManager;

    private LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    private String location;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_list);
        ButterKnife.bind(this);
        initDate();
        initView();
        initLocation();
        requestLocation(this);
    }

    /**
     * 从数据库中得到城市名等数据信息
     */
    private void initDate() {
        dbManager = new DBManager(this);
        dbManager.copyDBFile();
        mAllCities = dbManager.getAllCities();
        mCityAdapter = new CityListAdapter(this, mAllCities);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {
                back(name);
            }

            @Override
            public void onLocateClick() {
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
                mLocationClient.start();
            }
        });
        mResultAdapter = new ResultListAdapter(this, null);
    }

    private void initView() {
        listviewAllCity.setAdapter(mCityAdapter);
        sideLetterBar.setOverlay(tvLetterOverlay);
        sideLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                listviewAllCity.setSelection(position);
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    ivSearchClear.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    listviewSearchResult.setVisibility(View.GONE);
                } else {
                    ivSearchClear.setVisibility(View.VISIBLE);
                    listviewSearchResult.setVisibility(View.VISIBLE);
                    List<City> result = dbManager.searchCity(keyword);
                    if (result == null || result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });
        listviewSearchResult.setAdapter(mResultAdapter);
        listviewSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                back(mResultAdapter.getItem(position).getName());
            }
        });
    }


    /**
     * 定位
     */
    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        setLocationOption();
        mLocationClient.start();
        mLocationClient.requestLocation();
    }

    /**
     * 设置定位SDK的定位方式
     * <p>
     * 高精度定位模式：这种定位模式下，会同时使用网络定位和GPS定位，优先返回最高精度的定位结果；
     * 低功耗定位模式：这种定位模式下，不会使用GPS进行定位，只会使用网络定位（WiFi定位和基站定位）；
     * 仅用设备定位模式：这种定位模式下，不需要连接网络，只使用GPS进行定位，这种模式下不支持室内环境的定位。
     */
    private void setLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving); //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");  //可选，默认gcj02，设置返回的定位结果是百度经纬度
        option.setScanSpan(0);      //可选，默认0，即仅定位一次，设置发起定位请求的间隔时间为5000ms
        option.setIsNeedAddress(true); //可选，设置是否需要地址信息，默认不需要
        //option.setOpenGps(false);       //可选，默认false,设置是否使用gps
        //option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        //option.setIsNeedLocationDescribe(true); //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        //option.setIsNeedLocationPoiList(true);  //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        //option.setIgnoreKillProcess(false);     //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        //option.SetIgnoreCacheException(false);  //可选，默认false，设置是否收集CRASH信息，默认收集
        //option.setEnableSimulateGps(false);     //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @OnClick({R.id.back, R.id.iv_search_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.iv_search_clear:
                etSearch.setText("");
                ivSearchClear.setVisibility(View.GONE);
                emptyView.setVisibility(View.GONE);
                listviewSearchResult.setVisibility(View.GONE);
                break;
        }
    }


    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation != null) {
                if (bdLocation.getLocType() == 161){
                    //Toast.makeText(CityPickerActivity.this, "aaa" + bdLocation.getCity(), Toast.LENGTH_LONG).show();
                    //String s = bdLocation.getDistrict();  //得到区、县级单位
                    location = StringUtil.extractLocation(bdLocation.getCity());
                    mCityAdapter.updateLocateState(LocateState.SUCCESS, location);
                }else {
                    //定位失败
                    mCityAdapter.updateLocateState(LocateState.FAILED, null);
                    Toast.makeText(CityPickerActivity.this,"亲！网络定位失败，请重新连接网络"+bdLocation.getLocType(),Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void back(String city) {
        Intent data = new Intent();
        data.putExtra("city", city);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
    }

    private void requestLocation(final Context context){
        MPermissionUtils.requestPermissions(context, 0x01, new String[]{
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,}
                , new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        //
                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showLocServiceDialog(context);
                    }
                });
    }
}
